'use strict';
const uniID = require('uni-id-common');

exports.main = async (event, context) => {
  let body = event;
  if (event.body !== undefined) {
    body = JSON.parse(event.body);
  }

  const uniIDIns = uniID.createInstance({ context });
  const db = uniCloud.database();

  try {
    // 1. 身份验证
    const { uid } = await uniIDIns.checkToken(body.uniIdToken);
    if (!uid) {
      return { code: 403, msg: '身份验证失败' };
    }

    const { appointUserId, diagnosis } = body;
    if (!appointUserId || !diagnosis) {
      return { code: 400, msg: '缺少必要参数：appointUserId 或 diagnosis' };
    }

    // 2. 查询 appoint_schedule 中是否有记录
    const appointRes = await db.collection('appoint_schedule')
      .where({
        consultant: uid,
        uid: appointUserId
      })
      .get();

    if (appointRes.data.length > 0) {
      // 存在预约记录
      const { day, appointedSlot } = appointRes.data[0];

      // 3. 用完整 key 去查 appoint_records
      const recordRes = await db.collection('appoint_records')
        .where({
          consultant: uid,
          user: appointUserId,
          day,
          appointedSlot
        })
        .get();

      if (recordRes.data.length > 0) {
        // 找到记录，更新
        await db.collection('appoint_records').doc(recordRes.data[0]._id).update({
          diagnosis,
          update_time: new Date()
        });
        return { code: 0, msg: '已更新诊断记录（根据预约）' };
      } else {
        // 没有记录，创建新记录
        await db.collection('appoint_records').add({
          consultant: uid,
          user: appointUserId,
          day,
          appointedSlot,
          file_path: '',
          diagnosis,
          created_at: Date.now(),
          update_time: new Date()
        });
        return { code: 0, msg: '未找到诊断记录，已创建新记录（根据预约）' };
      }
    } else {
      // 没有预约记录，使用最近的一条诊断记录更新
      const latestRecordRes = await db.collection('appoint_records')
        .where({
          consultant: uid,
          user: appointUserId
        })
        .orderBy('created_at', 'desc')
        .limit(1)
        .get();

      if (latestRecordRes.data.length > 0) {
        await db.collection('appoint_records').doc(latestRecordRes.data[0]._id).update({
          diagnosis,
          update_time: new Date()
        });
        return { code: 0, msg: '已更新最近的诊断记录（无预约记录）' };
      } else {
        return {
          code: 404,
          msg: '没有预约记录，也没有诊断记录，无法更新'
        };
      }
    }
  } catch (e) {
    return {
      code: 500,
      msg: '服务器错误',
      error: e.message
    };
  }
};
